package com.cci.kangdao.utilTool;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Upload_Util {

	private static Logger log = Logger.getLogger(Upload_Util.class);

	//目录穿越检验
	public static boolean checkTraversal(String content){
		return content.contains("..") || content.contains("/");
	}


	/**
	 * 采用spring提供的上传文件的方法
	 * @param map
	 * @return
	 */
	public static String uploadData(Map<String, Object> map) {
		String name = "";
		try {
			String userId = null;
			if(map.containsKey("userId")){
				userId = (String) map.get("userId");
			}

			HttpServletRequest request = (HttpServletRequest)map.get("request");
			HttpServletResponse response = (HttpServletResponse)map.get("response");
			long startTime = System.currentTimeMillis();
			// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 检查form中是否有enctype="multipart/form-data"
			if (multipartResolver.isMultipart(request)) {
				// 将request变成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 获取multiRequest 中所有的文件名
				Iterator iter = multiRequest.getFileNames();

				//String basePath=request.getSession().getServletContext().getRealPath("upload");
				String basePath= ""+map.get("basePath");

				while (iter.hasNext()) {
					// 一次遍历所有文件
					MultipartFile file = multiRequest.getFile(iter.next().toString());
					if (file != null) {
						String fileName = file.getOriginalFilename().trim().replaceAll("[?/*\\\\:|<>\"\\\\^]", "_");
						if(StringUtils.isNotBlank(fileName) && checkTraversal(fileName)){
							ParameterTool.writeResponse(response, -2, "非法操作");
							return null;
						}
						// 文件名
						if(StringUtils.isNotBlank(userId)){
							name = userId +"_"+ Date_Util.GetTime(7,0)+"_"+ fileName;
						} else {
							name = Date_Util.GetTime(7,0)+"_"+ fileName;
						}

						// 上传
						file.transferTo(new File(basePath + File.separator + name));
					}else{
						log.error("上传文件为空");
					}
				}
			}else{
				log.error("request is not Multipart");
			}
			long endTime = System.currentTimeMillis();
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return "";
		}
		return name;
	}


	/**
	 * 采用spring提供的上传文件的方法
	 * @param map
	 * @return
	 */
	public static String uploadDataNoTime(Map<String, Object> map) {
		String name = "";
		try {
			String userId = null;
			if(map.containsKey("userId")){
				userId = (String) map.get("userId");
			}

			HttpServletRequest request = (HttpServletRequest)map.get("request");
			long startTime = System.currentTimeMillis();
			// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 检查form中是否有enctype="multipart/form-data"
			if (multipartResolver.isMultipart(request)) {
				// 将request变成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 获取multiRequest 中所有的文件名
				Iterator iter = multiRequest.getFileNames();

				//String basePath=request.getSession().getServletContext().getRealPath("upload");
				String basePath= ""+map.get("basePath");

				while (iter.hasNext()) {
					// 一次遍历所有文件
					MultipartFile file = multiRequest.getFile(iter.next().toString());
					if (file != null) {
						// 文件名
						if(StringUtils.isNotBlank(userId)){
							name = userId +"_"+file.getOriginalFilename();
						} else {
							name = file.getOriginalFilename();
						}

						// 上传
						file.transferTo(new File(basePath + File.separator + name));
					}else{
						log.error("上传文件为空");
					}
				}
			}else{
				log.error("request is not Multipart");
			}
			long endTime = System.currentTimeMillis();
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return "";
		}
		return name;
	}


	/**
	 * 采用spring提供的上传文件的方法
	 * @param map
	 * @return
	 */
	public static String newUploadData(Map<String, Object> map) {
		String name = "";
		try {
			String userId = null;
			if(map.containsKey("userId")){
				userId = (String) map.get("userId");
			}

			HttpServletRequest request = (HttpServletRequest)map.get("request");
			long startTime = System.currentTimeMillis();
			// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 检查form中是否有enctype="multipart/form-data"
			if (multipartResolver.isMultipart(request)) {
				// 将request变成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 获取multiRequest 中所有的文件名
				Iterator iter = multiRequest.getFileNames();

				//String basePath=request.getSession().getServletContext().getRealPath("upload");
				String basePath= ""+map.get("basePath");

				while (iter.hasNext()) {
					// 一次遍历所有文件
					MultipartFile file = multiRequest.getFile(iter.next().toString());
					if (file != null) {
						int suffixIndex = file.getOriginalFilename().lastIndexOf(".");
						//截取文件名称
						String fileName = file.getOriginalFilename().substring(0,suffixIndex);
						//截取文件后缀(包含.所在下标)
						String suffixName = file.getOriginalFilename().substring(suffixIndex);
						// 重新拼接文件名
						if(StringUtils.isNotBlank(userId)){
							name = fileName+"_"+userId +"_"+ Date_Util.GetTime(7,0)+suffixName;
						} else {
							name = fileName+"_"+Date_Util.GetTime(7,0)+suffixName;
						}

						// 上传
						file.transferTo(new File(basePath + File.separator + name));
					}else{
						log.error("上传文件为空");
					}
				}
			}else{
				log.error("request is not Multipart");
			}
			long endTime = System.currentTimeMillis();
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return "";
		}
		return name;
	}


	/**
	 * 采用spring提供的上传文件的方法
	 * @param map
	 * @return
	 */
	public static InputStream GetUploadInputStream(Map<String, Object> map) {
		InputStream in = null;
		try {
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			long startTime = System.currentTimeMillis();
			// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 检查form中是否有enctype="multipart/form-data"
			if (multipartResolver.isMultipart(request)) {
				// 将request变成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 获取multiRequest 中所有的文件名
				Iterator iter = multiRequest.getFileNames();

				while (iter.hasNext()) {
					// 一次遍历所有文件
					MultipartFile file = multiRequest.getFile(iter.next().toString());
					if (file != null) {
						in = file.getInputStream();
					}
				}
			}
			long endTime = System.currentTimeMillis();
			System.out.println("方法三的运行时间：" + String.valueOf(endTime - startTime) + "ms");
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return in;
	}

	public static List<String> uploadMultiData(Map<String, Object> map) {
		List<String> fileList = new ArrayList<>();
		try {
			HttpServletRequest request = (HttpServletRequest)map.get("request");
			long startTime = System.currentTimeMillis();
			// 将当前上下文初始化给 CommonsMultiPartResolver （多部分解析器）
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 检查form中是否有enctype="multipart/form-data"
			if (multipartResolver.isMultipart(request)) {
				// 将request变成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 获取multiRequest 中所有的文件名
				Iterator iter = multiRequest.getFileNames();

				//String basePath=request.getSession().getServletContext().getRealPath("upload");
				String basePath= ""+map.get("basePath");
				while (iter.hasNext()) {
					// 一次遍历所有文件
					MultipartFile file = multiRequest.getFile(iter.next().toString());
					if (file != null) {
						// 文件名
						String name = Date_Util.GetTime(7,0)+"_"+file.getOriginalFilename();
						// 上传
						file.transferTo(new File(basePath + File.separator + name));
						fileList.add(name);
					}
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return fileList;
	}
}
